<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="/js-test-resources/js-test.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script type="text/javascript">
description("WebSocket bufferedAmount after closed");

window.jsTestIsAsync = true;

function createStringWithLength(length)
{
    var string = 'x';
    while (string.length < length)
        string = string + string;
    return string.substring(0, length);
}

function createBlobWithLength(length)
{
    return new Blob([new Uint8Array(length)]);
}

var ws = new WebSocket("ws://localhost:8880/simple");

ws.onopen = function()
{
    debug("Connected.");
    ws.close();
};

ws.onclose = function()
{
    debug("Closed.");
    shouldBe("ws.readyState", "3");
    shouldBe("ws.bufferedAmount", "0");

    debug("Testing send(string)...");
    testBufferedAmount('send to closed socket', 21);
    testBufferedAmount('', 0);
    testBufferedAmount('a', 1);
    testBufferedAmount(createStringWithLength(125), 125);
    testBufferedAmount(createStringWithLength(126), 126); // With 16-bit extended payload length field.
    testBufferedAmount(createStringWithLength(0xFFFF), 0xFFFF);
    testBufferedAmount(createStringWithLength(0x10000), 0x10000); // With 64-bit extended payload length field.

    debug("Testing send(ArrayBuffer)...");
    testBufferedAmount(new ArrayBuffer(0), 0);
    testBufferedAmount(new ArrayBuffer(1), 1);
    testBufferedAmount(new ArrayBuffer(125), 125);
    testBufferedAmount(new ArrayBuffer(126), 126);
    testBufferedAmount(new ArrayBuffer(0xFFFF), 0xFFFF);
    testBufferedAmount(new ArrayBuffer(0x10000), 0x10000);

    debug("Testing send(Blob)...");
    testBufferedAmount(createBlobWithLength(0), 0);
    testBufferedAmount(createBlobWithLength(1), 1);
    testBufferedAmount(createBlobWithLength(125), 125);
    testBufferedAmount(createBlobWithLength(126), 126);
    testBufferedAmount(createBlobWithLength(0xFFFF), 0xFFFF);
    testBufferedAmount(createBlobWithLength(0x10000), 0x10000);

    finishJSTest();
};

var messageToSend;
var bufferedAmountDifference;

function testBufferedAmount(message, expectedBufferedAmountDifference)
{
    // If the connection is closed, bufferedAmount attribute's value will only
    // increase with each call to the send() method.
    // (the number does not reset to zero once the connection closes).
    messageToSend = message;
    var bufferedAmountBeforeSend = ws.bufferedAmount;
    shouldBeUndefined("ws.send(messageToSend)");
    var bufferedAmountAfterSend = ws.bufferedAmount;
    bufferedAmountDifference = bufferedAmountAfterSend - bufferedAmountBeforeSend;
    shouldEvaluateTo("bufferedAmountDifference", expectedBufferedAmountDifference);
}

</script>
</body>
</html>
